package logic

import (
	"context"
	"fmt"
	"wechat/models/mysql"
	"wechat/models/redisInit"
	"wechat/pkg"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	mobile := in.Mobile

	var user mysql.User

	if mobile != "" {
		mysql.DB.Where("mobile = ?", in.Mobile).Find(&user)

		if user.ID == 0 {
			return nil, fmt.Errorf("当前手机号不存在")
		}

		get := redisInit.Client.Get("sendSms" + "login" + in.Mobile)

		if get.Val() == "" {
			return nil, fmt.Errorf("请发送短信验证码")
		}

		if get.Val() != in.SmsCode {
			return nil, fmt.Errorf("当前短信验证码错误请重新输入")
		}
	} else {
		mysql.DB.Where("wechat_name = ?", in.Account).Find(&user)

		if user.ID == 0 {
			return nil, fmt.Errorf("当前账号不存在")
		}

		if user.PassWord != pkg.Md5(in.Password) {
			return nil, fmt.Errorf("密码错误")
		}
	}

	return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
